<template>
  <div class="update-photo">
    <img :src="imgUrl" ref="img" alt="" />
    <div class="toolabr">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="confirm">确定</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updateUserPhoto } from '@/api/user'
export default {
  name: "UpdatePhoto",
  props: {
    // 选择图片的预览地址
    imgUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      cropper:null
    }
  },
  mounted() {
    // 挂载之后处理
    const image = this.$refs.img
    this. cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    });
  },
  methods: {
    confirm(){
      this.$toast.loading({
        message:'处理中',
        duration:0
      })
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        try {
          let fd = new FormData()
          fd.append('photo',blob)
          const { data:res } = await updateUserPhoto(fd)
          this.$toast.success('更新头像成功')
          this.$emit('updatePhoto',res.data.photo)
        } catch (error) {
          this.$toast.fail('更新头像失败')
          
        }
      })
    }
  },
};
</script>
<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  img {
    max-width: 100%;
  }
  .toolabr {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
  }
  .cancel,
  .confirm {
    width: 120px;
    height: 90px;
    font-size: 0.4rem;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
